package com.dmcb.trade.business.crawlers.author;

import com.dmcb.common.business.constants.CommonConstant;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.crawlers.article.DouBanParser;
import com.dmcb.trade.business.entities.Article;
import com.dmcb.trade.business.entities.Author;
import com.dmcb.trade.business.mappers.ArticleCrawlMapper;
import com.dmcb.trade.controller.ArticleCrawlerController;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 豆瓣网日记解析
 * Created by 63221_000 on 2016/8/19 0019.
 */
@Service
public class DouBanNoteCrawler extends BaseCrawler {
    Logger logger = LoggerFactory.getLogger(ToutiaoCrawler.class);

    @Autowired
    private DouBanParser douBanParser;

    @Autowired
    private ArticleCrawlMapper articleCrawlMapper;

    @Autowired
    private ArticleCrawlerController articleCrawlerController;

    @Override
    protected String url() {
        return CrawlConstant.DOUBANNOTE_URL;
    }

    @Override
    protected int tag() {
        return CrawlConstant.DOUBANNOTE_TAG;
    }

    @Override
    protected JsonResult crawl(int authorId, String link, Author author, Document doc, boolean all) {
        // 爬取文章

        int size = 0;
        int totalAll = 0;
        int page=1;
        while (page <= CrawlConstant.CRAWL_PAGE_TOTAL) {
            JsonResult result = iterate(authorId, doc);
            if (!result.isSuccess()) {
                return result;
            }
            totalAll += result.getInt();
            //不能限制19，应该限制为1，只要此页添加成功一条都得继续下页爬取
            if (!all && result.getInt() < 1) {
                break;
            }
            size+=10;
            doc = Jsoup.parse(webClientUtil.getPage(link+"?start="+size+"&type=note").asXml(), baseUrl(link));
        }
        return totalAll == 0 ? error(CrawlConstant.MSG_WARN_NO_UPDATE) : success(totalAll);
    }

    /**
     * 迭代解析、保存文章
     *
     * @return 成功保存数量
     */
    protected JsonResult iterate(int authorId, Document doc, String listSelect, String titleSelect) {
        Elements elements = doc.select(listSelect);
        if (elements.size() == 0) {
            return success(0);
        }
        int succ = 0;
        int exist = 0;
        for (Element element : elements) {
            // 获取标题、链接元素
            Element ele = element.select(titleSelect).first();
            if (ele != null) {
                try {
                    // 校验作者、标题是否已存在
                    Article article = articleCrawlMapper.queryByAuthorTitle(authorId, ele.text().trim());
                    if (article != null) {
                        exist++;
                        if (exist >= 6 && succ == 0) {
                            return success(0);
                        }
                        continue;
                    }
                    String href = ele.absUrl("href");
                    JsonResult result = articleCrawlerController.douBanCrawlMonitor(authorId, href);
                    succ += result.isSuccess() ? 1 : 0;
                } catch (Exception e) {
                    logger.error("Parser.parse error,{}", ele, e);
                    return error(CommonConstant.ABNORMAL_MSG);
                }
            }
        }
        return success(succ);
    }

    @Override
    protected String avatarSelect() {
        return "div.pic>a>img";
    }

    @Override
    protected String channelNameSelect() {
        return "div.sd";
    }

    @Override
    protected String listSelect() {
        return "div.note-container";
    }

    @Override
    protected String titleSelect() {
        return "h3 >a";
    }

    @Override
    protected String authorLink() {
        return "div.note-header-container>div>a";
    }

    @Override
    protected String authorSelect() {
        return "div.sd";
    }

    @Override
    protected JsonResult parse(int authorId, String link) throws Exception {
        return douBanParser.parse(authorId, link);
    }
    @Override
    protected String check(String link) {
        if (!link.endsWith(url())) {
            return "链接地址错误，请重新输入";
        }
        return "";
    }

    @Override
    protected String getBody(Document doc) {
        return douBanParser.getBody(doc);
    }
}

